<template>
  <div class="forgot-password-container">
    <!-- Logo容器，位于页面最上方 -->
    <div class="logo-container fixed-top">
      <img src='@/assets/logo/logo.jpg' alt="logo" class="logo" />
    </div>
    
    <div class="main-content">
      <div class="form-section">
        <div class="form-container">
          <div class="form-header">
            <h2 class="form-title">找回密码</h2>
            <p class="form-subtitle">请输入注册邮箱以重置密码</p>
          </div>
          
          <!-- 步骤1：输入邮箱 -->
          <el-form 
            v-if="currentStep === 1"
            ref="emailFormRef" 
            :model="emailForm" 
            :rules="emailRules" 
            class="email-form"
            @keyup.enter="handleSendEmail"
          >
            <el-form-item prop="email">
              <el-input
                v-model="emailForm.email"
                prefix-icon="el-icon-message"
                placeholder="请输入注册邮箱"
                clearable
              />
            </el-form-item>
            
            <!-- 验证码 -->
            <el-form-item prop="captcha">
              <div class="captcha-container">
                <el-input
                  v-model="emailForm.captcha"
                  prefix-icon="el-icon-picture"
                  placeholder="验证码"
                  clearable
                />
                <div 
                  class="captcha-image"
                  @click="refreshCaptcha"
                  :style="{ background: captchaBgColor }"
                >
                  {{ captchaText }}
                </div>
              </div>
            </el-form-item>
            
            <div class="action-buttons">
              <el-button 
                type="primary" 
                :loading="isLoading" 
                :disabled="isLoading"
                class="submit-button"
                @click="handleSendEmail"
              >
                发送重置邮件
                <el-icon v-if="isLoading" class="loading-icon">
                  <el-loading></el-loading>
                </el-icon>
              </el-button>
            </div>
          </el-form>
          
          <!-- 步骤2：设置新密码 -->
          <el-form 
            v-else-if="currentStep === 2"
            ref="resetFormRef" 
            :model="resetForm" 
            :rules="resetRules" 
            class="reset-form"
            @keyup.enter="handleResetPassword"
          >
            <el-form-item prop="verificationCode">
              <el-input
                v-model="resetForm.verificationCode"
                prefix-icon="el-icon-key"
                placeholder="请输入验证码"
                clearable
              />
            </el-form-item>
            
            <el-form-item prop="newPassword">
              <el-input
                v-model="resetForm.newPassword"
                prefix-icon="el-icon-lock"
                suffix-icon="el-icon-view"
                :type="showPassword ? 'text' : 'password'"
                placeholder="请输入新密码"
                clearable
                @click:suffix="togglePasswordVisibility" 
              />
            </el-form-item>
            
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="resetForm.confirmPassword"
                prefix-icon="el-icon-lock"
                suffix-icon="el-icon-view"
                :type="showPassword ? 'text' : 'password'"
                placeholder="请再次输入新密码"
                clearable
                @click:suffix="togglePasswordVisibility" 
              />
            </el-form-item>
            
            <div class="action-buttons">
              <el-button 
                type="primary" 
                :loading="isLoading" 
                :disabled="isLoading"
                class="submit-button"
                @click="handleResetPassword"
              >
                重置密码
                <el-icon v-if="isLoading" class="loading-icon">
                  <el-loading></el-loading>
                </el-icon>
              </el-button>
            </div>
          </el-form>
          
          <!-- 步骤3：重置成功 -->
          <div v-else-if="currentStep === 3" class="success-message">
            <div class="success-icon">
              <el-icon>
                <el-check></el-check>
              </el-icon>
            </div>
            <h3 class="success-title">密码重置成功</h3>
            <p class="success-text">您的密码已成功重置，请使用新密码登录</p>
            <el-button 
              type="primary" 
              class="success-button"
              @click="navigateToLogin"
            >
              返回登录
            </el-button>
          </div>
          
          <!-- 登录链接 -->
          <div class="login-link">
            <el-link href="#" @click="navigateToLogin">返回登录</el-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();
const emailFormRef = ref(null);
const resetFormRef = ref(null);

// 当前步骤状态
const currentStep = ref(1); // 1: 输入邮箱, 2: 设置新密码, 3: 重置成功

// 表单数据
const emailForm = reactive({ 
  email: '',
  captcha: ''
});

const resetForm = reactive({ 
  verificationCode: '',
  newPassword: '',
  confirmPassword: ''
});

const isLoading = ref(false);
const showPassword = ref(false);

// 验证码相关状态
const captchaText = ref('');
const captchaBgColor = ref('');

// 表单验证规则
const emailRules = reactive({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, message: '验证码长度为4位', trigger: 'blur' }
  ]
});

const resetRules = reactive({
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码长度为6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== resetForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ]
});

// 发送重置邮件
const handleSendEmail = async () => {
  const valid = await emailFormRef.value.validate();
  if (!valid) return;
  
  // 验证验证码
  if (emailForm.captcha.toLowerCase() !== captchaText.value.toLowerCase()) {
    ElMessage.error('验证码错误');
    refreshCaptcha(); // 刷新验证码
    return;
  }
  
  isLoading.value = true;
  try {
    // 模拟发送邮件请求
    await new Promise(resolve => setTimeout(resolve, 1500));
    ElMessage.success('重置邮件已发送，请查收您的邮箱');
    currentStep.value = 2; // 进入下一步
  } catch (error) {
    ElMessage.error('发送邮件失败，请稍后再试');
  } finally {
    isLoading.value = false;
  }
};

// 重置密码
const handleResetPassword = async () => {
  const valid = await resetFormRef.value.validate();
  if (!valid) return;
  
  isLoading.value = true;
  try {
    // 模拟重置密码请求
    await new Promise(resolve => setTimeout(resolve, 1500));
    currentStep.value = 3; // 进入成功步骤
  } catch (error) {
    ElMessage.error('重置密码失败，请稍后再试');
  } finally {
    isLoading.value = false;
  }
};

const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

const navigateToLogin = () => {
  router.push('/login');
};

// 生成随机验证码
const generateCaptcha = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < 4; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};

// 生成随机背景色
const generateRandomColor = () => {
  const h = Math.floor(Math.random() * 360);
  const s = 70 + Math.floor(Math.random() * 30);
  const l = 70 + Math.floor(Math.random() * 20);
  return `hsl(${h}, ${s}%, ${l}%)`;
};

// 刷新验证码
const refreshCaptcha = () => {
  captchaText.value = generateCaptcha();
  captchaBgColor.value = generateRandomColor();
};

// 初始化验证码
const initCaptcha = () => {
  refreshCaptcha();
};

// 组件挂载时初始化验证码
initCaptcha();
</script>

<style scoped>
.forgot-password-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-image: url('../assets/img/background.png');
  background-size: cover;
  overflow: hidden;
}

/* Logo容器 - 顶部固定定位，无内边距，紧贴顶部边缘 */
.logo-container.fixed-top {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  text-align: center;
  margin: 0; /* 移除外边距 */
  padding: 0; /* 移除内边距 */
  z-index: 100; /* 确保在最上层 */
  background: rgba(255, 255, 255, 0.9); /* 可选：半透明背景 */
}

.logo {
  max-height: 50px; /* 设置Logo最大高度，根据实际需求调整 */
  width: auto;
  margin: 0; /* 移除外边距 */
  padding: 0; /* 移除内边距 */
}

/* 主内容区域 - 调整顶部间距，避免被Logo遮挡 */
.main-content {
  margin-top: 60px; /* 根据Logo高度调整，确保不遮挡 */
  background: white;
  padding: 28px;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0,0,0,0.1);
  width: 90%;
  max-width: 320px;
}

.form-header {
  text-align: center;
  margin-bottom: 20px;
}

.form-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1D2939;
}

.form-subtitle {
  margin-top: 4px;
  font-size: 0.9rem;
  color: #667085;
}

.email-form .el-form-item,
.reset-form .el-form-item {
  margin-bottom: 16px;
}

.email-form .el-input,
.reset-form .el-input {
  height: 42px;
  border-radius: 6px;
  border: 1px solid #e0e0e0;
  font-size: 0.95rem;
}

.email-form .el-input:focus-within,
.reset-form .el-input:focus-within {
  border-color: #165DFF;
  box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.1);
}

/* 验证码容器 */
.captcha-container {
  display: flex;
  gap: 10px;
}

/* 验证码输入框 */
.captcha-container .el-input {
  flex: 1;
}

/* 验证码图片 */
.captcha-image {
  width: 100px;
  height: 42px;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: Arial, sans-serif;
  font-weight: bold;
  font-size: 18px;
  color: #333;
  cursor: pointer;
  user-select: none;
  letter-spacing: 2px;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
}

/* 操作按钮 */
.action-buttons {
  margin-top: 24px;
}

.submit-button {
  width: 100%;
  height: 42px;
  font-size: 0.95rem;
  background-color: #165DFF;
  border: none;
  border-radius: 6px;
  color: white;
  cursor: pointer;
  transition: all 0.2s;
}

.submit-button:hover {
  background-color: #0E42D2;
  box-shadow: 0 3px 8px rgba(22, 93, 255, 0.15);
}

/* 成功消息 */
.success-message {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  width: 60px;
  height: 60px;
  margin: 0 auto 16px;
  background-color: #27AE60;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.success-icon .el-icon {
  color: white;
  font-size: 24px;
}

.success-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #1D2939;
  margin-bottom: 8px;
}

.success-text {
  font-size: 0.9rem;
  color: #667085;
  margin-bottom: 24px;
}

.success-button {
  width: 100%;
  height: 42px;
  font-size: 0.95rem;
  background-color: #165DFF;
  border: none;
  border-radius: 6px;
  color: white;
  cursor: pointer;
  transition: all 0.2s;
}

.success-button:hover {
  background-color: #0E42D2;
  box-shadow: 0 3px 8px rgba(22, 93, 255, 0.15);
}

/* 登录链接 */
.login-link {
  text-align: center;
  margin-top: 16px;
  color: #667085;
  font-size: 0.9rem;
}

.login-link .el-link {
  color: #165DFF;
  font-weight: 500;
  text-decoration: none;
}

.login-link .el-link:hover {
  text-decoration: underline;
}
</style>
